﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities.Shell
{
    public class Instruction : IRunnable
    {
        public Scope Scope { get; private set; }

        public string Command { get; private set; }
        public string Parameter { get; private set; }

        public Instruction(Scope scope, string instruction)
        {
            Scope = scope;

            Command = instruction.Trim();
            Parameter = "";

            if (Command.Contains(' ') || Command.Contains('\t'))
            {
                Parameter = instruction.Substring(Command.IndexOfAny(' ', '\t')).Trim();
                Command = instruction.Remove(Command.IndexOfAny(' ', '\t')).Trim();
            }
        }
        public Instruction(Scope scope, string command, string parameter)
        {
            Scope = scope;

            Command = command.Trim();
            Parameter = parameter.Trim();
        }

        public void Run(string replacement)
        {
            string command = Command.Replace("?", replacement);
            string parameter = Parameter.Replace("?", replacement);

            if (Scope.Shell.CommandHandlers.ContainsKey(command))
                Scope.Shell.CommandHandlers[command](Scope, parameter);
            else
                Console.WriteLine("Unhandled command " + '"' + command + '"');
        }

        public override string ToString()
        {
            if (Parameter == null || Parameter == "")
                return Command;
            else
                return Command + ' ' + Parameter;
        }
    }
}